package org.lld.im.service.conversation.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lld.im.codec.pack.conversation.DeleteConversationPack;
import com.lld.im.codec.pack.conversation.UpdateConversationPack;
import org.lld.im.common.ResponseVO;
import org.lld.im.common.config.AppConfig;
import org.lld.im.common.constant.Constants;
import org.lld.im.common.enums.ConversationErrorCode;
import org.lld.im.common.enums.ConversationTypeEnum;
import org.lld.im.common.enums.command.ConversationEventCommand;
import org.lld.im.common.model.ClientInfo;
import org.lld.im.common.model.message.MessageReadedContent;
import org.lld.im.service.conversation.dao.ImConversationSetEntity;
import org.lld.im.service.conversation.dao.mapper.ImConversationSetMapper;
import org.lld.im.service.conversation.model.DeleteConversationReq;
import org.lld.im.service.conversation.model.UpdateConversationReq;
import org.lld.im.service.seq.RedisSeq;
import org.lld.im.service.utils.MessageProducer;
import org.lld.im.service.utils.WriteUserSeq;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.RequestContextFilter;

import javax.annotation.Resource;

/**
 * @author: LunBoWang
 * @description: TODO
 * @date: 2025/4/7 下午6:28
 * @version: 1.0
 */
@Service
public class ConversationService {

    @Resource
    ImConversationSetMapper imConversationSetMapper;

    @Resource
    MessageProducer messageProducer;

    @Resource
    AppConfig appConfig;

    @Resource
    RedisSeq redisSeq;

    @Resource
    WriteUserSeq writeUserSeq;
    @Autowired
    private RequestContextFilter requestContextFilter;

    public String convertConversaionId(Integer type, String fromId, String toId) {
        return type + "_" + fromId + "_" + toId;
    }

    public void messageMarkRead(MessageReadedContent messageReadedContent) {

        String toId = messageReadedContent.getToId();
        if (messageReadedContent.getConversationType() == ConversationTypeEnum.GROUP.getCode()) {
            toId = messageReadedContent.getGroupId();
        }
        String conversaionId = convertConversaionId(messageReadedContent.getConversationType(),
                messageReadedContent.getFromId(), toId);
        QueryWrapper<ImConversationSetEntity> query = new QueryWrapper<>();
        query.eq("conversation_id", conversaionId);
        query.eq("app_id", messageReadedContent.getAppId());
        ImConversationSetEntity imConversationSetEntity = imConversationSetMapper.selectOne(query);
        if (imConversationSetEntity == null) {
            imConversationSetEntity = new ImConversationSetEntity();
            long seq=redisSeq.doGetSeq(messageReadedContent.getAppId()+":"+ Constants.SeqConstants.Conversation);
            imConversationSetEntity.setConversationId(conversaionId);
            BeanUtils.copyProperties(messageReadedContent, imConversationSetEntity);
            imConversationSetEntity.setReadedSequence(messageReadedContent.getMessageSequence());
            imConversationSetEntity.setSequence(seq);
            imConversationSetMapper.insert(imConversationSetEntity);
            writeUserSeq.writeUserSeq(messageReadedContent.getAppId(),
                    messageReadedContent.getFromId(),Constants.SeqConstants.Conversation,seq);
        } else {
            long seq=redisSeq.doGetSeq(messageReadedContent.getAppId()+":"+ Constants.SeqConstants.Conversation);
            imConversationSetEntity.setReadedSequence(messageReadedContent.getMessageSequence());
            imConversationSetEntity.setSequence(seq);
            imConversationSetMapper.readMark(imConversationSetEntity);
            writeUserSeq.writeUserSeq(messageReadedContent.getAppId(),
                    messageReadedContent.getFromId(),Constants.SeqConstants.Conversation,seq);
        }
    }

    //删除会话
    public ResponseVO deleteConversation(DeleteConversationReq req) {

//        QueryWrapper<ImConversationSetEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("conversation_id", req.getConversationId());
//        queryWrapper.eq("app_id", req.getAppId());
//        ImConversationSetEntity imConversationSetEntity = imConversationSetMapper.selectOne(queryWrapper);
//        if (imConversationSetEntity != null) {
//            imConversationSetEntity.setIsMute(0);
//            imConversationSetEntity.setIsTop(0);
//            imConversationSetMapper.update(imConversationSetEntity, queryWrapper);
//        }

        if (appConfig.getDeleteConversationSyncMode() == 1) {
            DeleteConversationPack pack = new DeleteConversationPack();
            pack.setConversationId(req.getConversationId());
            messageProducer.sendToUserExceptClient(req.getFromId(),
                    ConversationEventCommand.CONVERSATION_DELETE,
                    pack, new ClientInfo(req.getAppId(), req.getClientType(),
                            req.getImei()));
        }

        return ResponseVO.successResponse();
    }

    //更新会话，置顶or免打扰
    public ResponseVO updateConversation(UpdateConversationReq req) {

        if (req.getIsTop() == null && req.getIsMute() == null) {
            //返回失败
            return ResponseVO.errorResponse(ConversationErrorCode.CONVERSATION_UPDATE_PARAM_ERROR);
        }

        QueryWrapper<ImConversationSetEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("conversation_id", req.getConversationId());
        queryWrapper.eq("app_id", req.getAppId());
        ImConversationSetEntity imConversationSetEntity = imConversationSetMapper.selectOne(queryWrapper);
        if (imConversationSetEntity != null) {
            long seq=redisSeq.doGetSeq(req.getAppId()+":"+ Constants.SeqConstants.Conversation);
            if (req.getIsMute() != null) {
                imConversationSetEntity.setIsMute(req.getIsMute());
            }
            if (req.getIsTop() != null) {
                imConversationSetEntity.setIsTop(req.getIsTop());
            }
            imConversationSetEntity.setSequence(seq);
            imConversationSetMapper.update(imConversationSetEntity, queryWrapper);
            writeUserSeq.writeUserSeq(req.getAppId(),
                    req.getFromId(),Constants.SeqConstants.Conversation,seq);

            UpdateConversationPack pack = new UpdateConversationPack();
            pack.setConversationId(req.getConversationId());
            pack.setIsMute(imConversationSetEntity.getIsMute());
            pack.setIsTop(imConversationSetEntity.getIsTop());
            pack.setSequence(seq);
            pack.setConversationType(imConversationSetEntity.getConversationType());
            messageProducer.sendToUserExceptClient(req.getFromId(),
                    ConversationEventCommand.CONVERSATION_UPDATE,
                    pack, new ClientInfo(req.getAppId(), req.getClientType(),
                            req.getImei()));

        }
        return ResponseVO.successResponse();
    }
}
